package homegroup.inc.servlets;

import homegroup.inc.dao.BookDAO;
import homegroup.inc.dto.Book;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * Created by stone on 19.01.2015.
 */
@WebServlet(urlPatterns = "/download/*")
public class BookDownload extends HttpServlet {
    @EJB
    BookDAO bookDAO;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String isbn = req.getParameter("isbn");
        Book book = bookDAO.findByISBN(isbn);
        File bookFile = new File(book.getBookPath());
        File coverFile = new File(book.getCoverPath());
        File[] files = {bookFile, coverFile};
        int pos = bookFile.getName().lastIndexOf(".");
        String archiveName = bookFile.getName().substring(0, pos);

        String bookName = bookFile.getName();
        ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(new File("C:\\Temp\\Test\\" + archiveName + ".zip")));

        for (File file : files) {
            outputStream.putNextEntry(new ZipEntry(file.getName()));
            FileInputStream inputStream = new FileInputStream(file);
            int size = 0;
            byte[] buffer = new byte[1024];
            while((size = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, size);
            }
            inputStream.close();
        }
        outputStream.closeEntry();
        outputStream.close();
    }
}
